package controllers

import (
	"chat-room/http/dao"
	"chat-room/http/dto"
	"chat-room/lib"
	"chat-room/providers"
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/gorm"
	"strconv"
	"time"
)

type User struct {
	Base
}

/**
 * @Author: yang
 * @Description：聊天室用户添加
 * @Date: 2021/10/26 11:37
 */
func (u *User) UserAdd(c *gin.Context) {
	// dto 数据绑定和校验
	var form dto.UserAddInput
	if err := c.Bind(&form); err != nil {
		u.BadResponse(10000, err.Error(), c)
		return
	}
	if err := form.CheckUserAddInput(); err != nil {
		u.BadResponse(10004, err.Error(), c)
		return
	}

	// dao 数据处理
	tx := providers.Mysql
	token := lib.GenSaltToken(lib.GetRandomString(5), strconv.FormatInt(time.Now().Unix(), 10))
	userDao := &dao.User{
		RoomId: form.RoomId,
		Name:   form.UserName,
		Token:  token,
	}
	userInfo, sqlErr := userDao.Find(tx, userDao)
	if sqlErr != nil && sqlErr != gorm.ErrRecordNotFound {
		u.BadResponse(20003, sqlErr.Error(), c)
		return
	}

	if sqlErr == nil && userInfo != nil {
		u.BadResponse(20003, "用户名称已经存在~", c)
		return
	}

	if addErr := userDao.Save(tx); addErr != nil {
		u.BadResponse(20003, addErr.Error(), c)
		return
	}

	// 结果返回
	u.SuccessResponse(token, c)
	return
}
